import React, {Component} from 'react';
import {connect} from 'dva';
import {routerRedux} from 'dva/router'
import {Row,Col,Card,Tabs,Input,Radio,DatePicker,Table,Pagination} from 'antd'
import Mock from 'mockjs'
import moment from 'moment'
import fx from '../../../components/investmentAnalysis/utils/fx'


import style from './home.less'

import Pie from '../../../components/common/Pie'

import {Tabtitle,NoData} from '../../../components'
import {ReplayInfo,ToolbarWithRangePicker,PieCharts,KCharts,TradeDetail} from '../components'

const StockDistribution=({
	title="",
	data=[],
	})=>{
	const myProps={
		data:data.map(item=>({
			name:item.stockName||item.stockCode,
			value:item.pnl||item.ratio,
			ratio:item.ratio,
		})).sort(function(a,b){
			return b.value-a.value
		}),
	}
	return(
		<Card title={title}  >
			<Pie {...myProps}/>
		</Card>

	)
}

const TabPane = Tabs.TabPane;

const ReplayTabs=({
	sharesListProps,
	tradesListProps,
	positionListprops,
	tradeData,
	account,
	trader,
	begindate,
	enddate,
	dispatch,
	tag,
	location,
	filterValue,
	sortField,
	sortOrder,
	income,
	loss,
	})=>{

	const onExpand=(e,record)=>{
		if(!tradeData.filter(item=>(item.trader===record.trader)&&(item.orderId===record.closeOrderId)).length){

			dispatch({
				type:`${tag}/queryDetail`,
				payload:{
					trader:record.trader,
					orderId:record.closeOrderId,
					closeOrderId:record.closeOrderId,
					openOrderId:record.openOrderId,
					stockCode:record.symbol,
					openTime:moment(record.openTime).format('YYYY-MM-DD HH:mm'),
					buyPrice:record.buyPrice,
					closeTime:moment(record.closeTime).format('YYYY-MM-DD HH:mm'),
					sellPrice:record.sellPrice,
					from:moment(record.openTime),
					to:moment(record.closeTime)
				}
			})
		}
	}

	const changeTable=(a,b,c,d)=>{
		console.log(111,a,b,c,d);
		dispatch({
			type:`${tag}/changeRouter`,
			payload:{
				pathname:location.pathname,
				query:{
					trader,
					begindate,
					enddate,
					filterValue,
					currentpage:a.current,
					pagesize:a.pageSize,
					sortField:c.field,
					sortOrder:c.order
				}
			}
		})
	}
	const changePage=(a,b)=>{
		dispatch({
			type:`${tag}/changeRouter`,
			payload:{
				pathname:location.pathname,
				query:{
					trader,
					begindate,
					enddate,
					filterValue,
					currentpage:a,
					pagesize:b,
					sortField,
					sortOrder
				}
			}
		})
	}


	return(
		<Row className={style.tabs}>
			<Col>
				<Tabs
					defaultActiveKey="1"
					// onChange={tabChange}
					>
					<TabPane tab="交易股票详情" key="1">
						<Table
							{...sharesListProps}
							pagination={{
								showSizeChanger:true,
								defaultCurrent:1,
								total:sharesListProps.dataSource.length,
								pageSize:10,
								showTotal:total => `共 ${total} 条记录`
							}}
						/>
					</TabPane>

					<TabPane tab="分析图表" key="4">
						<Row className={style.info} gutter={30} style={{marginBottom:20}}>
							<Col span={12}>
								<StockDistribution title="股票盈利分布" data={income}/>
							</Col>
							<Col span={12}>
								<StockDistribution title="股票亏损分布" data={loss}/>
							</Col>
						</Row>

					</TabPane>

					<TabPane tab="交易详情" key="3">
						<Table
							{...tradesListProps}
							expandedRowRender={record => {
								return(
									<TradeDetail
										tradesListProps={tradesListProps}
										data={tradeData.find(item=>(item.trader===record.trader)&&(item.orderId===record.closeOrderId))}
									/>
								)
							}}
							expandRowByClick={true}
							onExpand={onExpand}
							onChange={changeTable}
							pagination={false}/>
							<Pagination
								showSizeChanger={true}
								current={tradesListProps.page.currentpage}
								total={tradesListProps.page.totalnum}
								pageSize={tradesListProps.page.pagesize}
								showTotal={total => `共 ${total} 条记录`}
								onChange={changePage}
								onShowSizeChange={changePage}
							/>
					</TabPane>
					<TabPane tab="未平仓详情" key="2">
						<Row className={style.info} gutter={30}>
							<Col span={9}>
								<h3>未平仓分布</h3>
								<PieCharts  data={positionListprops.dataSource}/>
							</Col>
							<Col span={14}>
								<h3 style={{marginBottom:10}}>剩余持仓</h3>
								<Table
									{...positionListprops}
									pagination={{
										showSizeChanger:true,
										defaultCurrent:1,
										total:positionListprops.dataSource.length,
										pageSize:10,
										showTotal:total => `共 ${total} 条记录`
									}}
									size="small"
								/>
							</Col>
						</Row>

					</TabPane>
				</Tabs>
			</Col>
		</Row>
	)
}

const ReplayDetail = ({dispatch,replayDetail,location}) =>{
	const {
		filterValue,
		begindate,
		enddate,
		info,
		shares,
		loss,
		income,
		trades,
		tradeArr,
		openPosition,
		account,
		sortField,
		sortOrder
	}=replayDetail
	const tag='replayDetail'
	const infoData=info&&info.trader?[
		{
			name:'交易员',
			value:info.trader
		},
		{
			name:'基金编号',
			value:info.groupid
		},
		{
			name:'持仓',
			value:info.holdsNum+'只'
		},
		{
			name:'起始资金',
			value:info.beginCash
		},
		{
			name:'交易总市值',
			value:info.tradeTotalMarketValue
		},
		{
			name:'市值利用率',
			value:info.utilizationRatio
		},
		{
			name:'总盈利',
			value:info.allTimePnl
		},
		{
			name:'日盈亏',
			value:info.dayPnl
		},
		{
			name:'盈亏比',
			value:info.profitLossRatio
		},

		{
			name:'市值收益率',
			value:info.marketValueYield
		},
		{
			name:'获利收益率',
			value:info.profitYield
		},
		{
			name:'亏损收益率',
			value:info.lossYield
		},
		{
			name:'平均收益率',
			value:info.averageReturnRate
		},
		{
			name:'交易次数',
			value:info.tradeCount
		},
		{
			name:'获利次数',
			value:info.reapProfit
		},
		{
			name:'交易胜率',
			value:info.winRatio
		},
		{
			name:'历史天数',
			value:info.historyDays+'天'
		},
		{
			name:'连赢天数',
			value:info.streak+'天'
		},
		{
			name:'天数胜率',
			value:info.winningDayRatio
		},
		{
			name:'收益率最大单笔亏损',
			value:info.maximumLoss
		}
	]:[]
	const replayTabsProps={
		sharesListProps:{
			dataSource:shares||[],
			columns:[
			  {
			    title: '代码',
			    dataIndex: 'symbol',
			    key: 'symbol',
					sorter: (a, b) => a.symbol - b.symbol,
			  },
			  {
			    title: '原始股数',
			    dataIndex: 'initialQuantity',
			    key: 'initialQuantity',
			  	sorter: (a, b) => a.initialQuantity - b.initialQuantity,
			  },
				{
			    title: '买入',
			    dataIndex: 'buy',
			    key: 'buy',
			  	sorter: (a, b) => a.buy - b.buy,
					render: text => Number(text).toFixed(2)
			  },
				{
			    title: '卖出',
			    dataIndex: 'sell',
			    key: 'sell',
			  	sorter: (a, b) => a.sell - b.sell,
					render: text => Number(text).toFixed(2)
			  },
				{
			    title: '净买入',
			    dataIndex: 'theNetBuying',
			    key: 'theNetBuying',
			  	sorter: (a, b) => a.theNetBuying - b.theNetBuying,
			  },
				{
			    title: '交易余量',
			    dataIndex: 'tradeMargin',
			    key: 'tradeMargin',
			  	sorter: (a, b) => a.tradeMargin - b.tradeMargin,
			  },
				{
			    title: '股数利用率',
			    dataIndex: 'utilizationRatio',
			    key: 'utilizationRatio',
			  	sorter: (a, b) => a.utilizationRatio - b.utilizationRatio,
			  },
			  {
			    title: '交易次数',
			    dataIndex: 'tradeCount',
			    key: 'tradeCount',
			  	sorter: (a, b) => a.tradeCount - b.tradeCount,
			  },
			  {
			    title: '胜率',
			    dataIndex: 'winRatio',
			    key: 'winRatio',
			  	sorter: (a, b) => a.winRatio - b.winRatio,
			  },
			  {
			    title: '收盘市值',
			    dataIndex: 'closeMarketValue',
			    key: 'closeMarketValue',
			  	sorter: (a, b) => a.closeMarketValue - b.closeMarketValue,
			  },
				{
			    title: '盈利',
			    dataIndex: 'pnl',
			    key: 'pnl',
					sorter: (a, b) => a.pnl - b.pnl,
			  },
				{
			    title: '收益率',
			    dataIndex: 'yield',
			    key: 'yield',
					sorter: (a, b) => a.yield - b.yield,
			  }
			],
			rowKey:"symbol"
		},
		tradesListProps:{
			dataSource:trades&&trades.data||[],
			columns:[
			  {
			    title: '股票代码',
			    dataIndex: 'symbol',
			    key: 'symbol',
					sorter: (a, b) => a.symbol - b.symbol,
			  },
			  {
			    title: '交易类型',
			    dataIndex: 'tradeType',
			    key: 'tradeType',
			  	sorter: (a, b) => a.tradeType - b.tradeType,
					render: (text, row, index) => ({ Buy: '做多', Sell: '做空' })[text]
			  },
				{
			    title: '买入价格',
			    dataIndex: 'buyPrice',
			    key: 'buyPrice',
			  	sorter: (a, b) => a.buyPrice - b.buyPrice,
					render: text => Number(text).toFixed(2),
			  },
				{
			    title: '卖出价格',
			    dataIndex: 'sellPrice',
			    key: 'sellPrice',
			  	sorter: (a, b) => a.sellPrice - b.sellPrice,
					render: text => Number(text).toFixed(2),
			  },
				{
			    title: '交易量',
			    dataIndex: 'quantity',
			    key: 'quantity',
			  	sorter: (a, b) => a.quantity - b.quantity,
			  },
				{
			    title: '费用',
			    dataIndex: 'fee',
			    key: 'fee',
			  	sorter: (a, b) => a.fee - b.fee,
					render: text => Number(text).toFixed(2)
			  },
				{
			    title: '盈亏',
					dataIndex: 'pnl',
					key:row => (row.sellPrice + row.buyPrice),
					sorter: (a, b) => ((a.sellPrice - a.buyPrice) * a.quantity - a.fee) - ((b.sellPrice - b.buyPrice) * b.quantity - b.fee),
			    render: (text, row) => {
			      const { tradeType, buyPrice, sellPrice, quantity, fee } = row;
			      return fx.colorMoney((sellPrice - buyPrice) * quantity - fee);
			    },
			  },
				{
			    title: '收益率',
					key:row => (row.buyPrice + row.quantity),
			    sorter: (a, b) => a.pnl / (a.buyPrice * a.quantity) - b.pnl / (b.buyPrice * b.quantity),
			    render: (text, row) => {
			      const { tradeType, buyPrice, sellPrice, quantity, pnl } = row;
			      return fx.formatRoi(pnl / (buyPrice * quantity));
			    },
			  },
			  {
			    title: '建仓时间',
					dataIndex: 'openTime',
			    key: 'openTime',
			  	sorter: (a, b) => a.openTime > b.openTime?1:-1,
					render: (text, record) => {
						return moment(record.openTime).format('YYYY-MM-DD HH:mm:ss')
					}
			  },
			  {
			    title: '平仓时间',
					dataIndex: 'closeTime',
			    key: 'closeTime',
			  	sorter: (a, b) => a.closeTime > b.closeTime?1:-1,
					render: (text, record) => {
						return moment(record.closeTime).format('YYYY-MM-DD HH:mm:ss')
					}
			  },
				{
		    title: '持仓时间',
				key:row => (row.closeTime + row.openTime),
				sorter: (a, b) => (moment(a.closeTime) - moment(a.openTime)) / 1000-(moment(b.closeTime) - moment(b.openTime)) / 1000,
		    render: (text, row) => {
		      const { openTime, closeTime } = row;
					const odate=moment(openTime).format('YYYYMMDD')*1
					const cdate=moment(closeTime).format('YYYYMMDD')*1

					if(odate===cdate){
						const oh=moment(openTime).format('HH')*1
						const ch=moment(closeTime).format('HH')*1
						if(oh<12&&ch>12){
							return fx.formatSeconds((moment(closeTime) - moment(openTime)) / 1000-90*60)
						}else{
							return fx.formatSeconds((moment(closeTime) - moment(openTime)) / 1000)
						}
					}else{
						return fx.formatSeconds((moment(closeTime) - moment(openTime)) / 1000)
					}

		    },
		  }
			],
			rowKey:row => (row.closeOrderId + row.openOrderId),
			page:(trades&&trades.page)||{pagesize: 10, currentpage: 1, totalpage: 0, totalnum: 0}
		},
		positionListprops:{
			dataSource: openPosition||[],
			columns:[
				{
					title: '股票代码',
					dataIndex: 'symbol',
					key: 'symbol',
				},
				{
					title: '类型',
					dataIndex: 'tradeType',
					key: 'tradeType',
					render: (text, record) =>text==='Buy'?<span style={{color:"green"}}>做空</span>:<span style={{color:"red"}}>做多</span>
				},
				{
					title: '价格',
					dataIndex: 'price',
					key: 'price'
				},
				{
					title: '交易数量',
					dataIndex: 'quantity',
					key: 'quantity'
				},
				{
					title: '费用',
					dataIndex: 'fee',
					key: 'fee',
					render: text => Number(text).toFixed(2)
				},
				{
					title: '浮动盈亏',
					dataIndex: 'buyPrice',
					key: 'buyPrice',
					render: (text, record) => {
						const { tradeType, price, currentPrice, quantity, fee } = record;
						// return fx.colorMoney((currentPrice - price) * quantity - fee)
						if (tradeType === 'Buy') {
							return fx.colorMoney((currentPrice - price) * quantity - fee);
						} else {
							return fx.colorMoney((price - currentPrice) * quantity - fee);
						}
					}
				},
				{
					title: '建仓时间',
					dataIndex: 'timestamp',
					key: 'timestamp',
					render: (text, record) => moment(text).format('YYYY-MM-DD hh:mm:ss')
				}
			],
			rowKey:"orderId"
		},

		tradeData:tradeArr,
		trader:location.query.trader,
		begindate,
		enddate,
		dispatch,
		tag,
		location,
		filterValue,
		sortField,
		sortOrder,
		income,
		loss,
	}
	const toolbarProps={
    begindate:begindate||(info&&info.dataDate),
    enddate:enddate||(info&&info.dataDate),
    dataDate:info&&info.dataDate,
    filterValue,
    dispatch,
    location,
    tag,
  }
	return (
		<div className={`equity ${style.detail}`}>
			<Tabtitle value={'证投复盘详情'}/>
			<div className="content-inner">
				<Row>
					<Col>
						<Card title="交易员详情" bordered={false}   extra={<ToolbarWithRangePicker
		          {...toolbarProps}
		        />}>
							{
								infoData&&infoData.length?<ReplayInfo data={infoData} />:<NoData />
							}
						</Card>
					</Col>
				</Row>
				<Row>
					<Col>
						<ReplayTabs {...replayTabsProps}/>
					</Col>
				</Row>
			</div>
		</div>
	)

}

ReplayDetail.propTypes = {
};

export default connect(({replayDetail}) => ({replayDetail}))(ReplayDetail);
